<template>
  <el-form ref="qmGenForm" :model="model" :rules="rules" :disabled="disabled">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="向导名称" prop="guideName" label-width="100px">
          <el-input v-model="model.guideName" placeholder="请输入向导名称" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="模块路径" prop="modulePath" label-width="100px">
          <el-select
            v-model="model.modulePath"
            placeholder="请选择模块路径"
            filterable
            clearable
          >
            <el-option
              v-for="(item, index) in leavesRouterPaths"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="是否所有用户">
          <el-switch
            v-model="model.isEveryone"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="onIsEveryoneChange"
          >
          </el-switch>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          label="用户"
          prop="userIds"
          label-width="100px"
          v-show="!model.isEveryone"
        >
          <el-select
            v-model="model.userIds"
            placeholder="请选择用户"
            multiple
            filterable
            clearable
            collapse-tags
          >
            <el-option
              label="全选"
              value="全选"
              @click.native="selectAllUser"
            ></el-option>
            <el-option
              v-for="item in viewModel.controlData.userOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="触发类型" prop="triggerType" label-width="100px">
          <el-select v-model="model.triggerType" placeholder="请选择触发类型">
            <el-option
              v-for="item in viewModel.controlData.triggerTypes"
              :key="item.key"
              :label="item.key"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <div class="mix-item">
      <el-form-item label="向导类型" prop="guideType" label-width="100px">
        <el-select
          v-model="model.guideType"
          placeholder="请选择向导类型"
          @change="onGuideTypeChange"
          :disabled="true"
        >
          <el-option
            v-for="item in viewModel.controlData.guideTypes"
            :key="item.key"
            :label="item.key"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort" label-width="100px">
        <el-input-number v-model="model.sort" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnabled" label-width="100px">
        <el-switch
          v-model="model.isEnabled"
          active-color="#13ce66"
          inactive-color="#ff4949"
        >
        </el-switch>
      </el-form-item>
      <!-- <el-form-item
        v-if="model.guideType === HINTS_GUIDE_TYPE"
        label="复用hints"
        prop="reuseHints"
        label-width="100px"
      >
        <el-switch
          v-model="model.reuseHints"
          active-color="#13ce66"
          inactive-color="#ff4949"
        >
        </el-switch>
      </el-form-item> -->
    </div>

    <div class="element-btns">
      <el-button
        type="primary"
        size="small"
        @click="handleSetAttr"
        :disabled="false"
      >
        {{ disabled ? "查看属性" : "设置属性" }}
      </el-button>
      <el-button
        type="success"
        size="small"
        @click="handleSetEvents"
        :disabled="false"
      >
        {{ disabled ? "查看事件" : "设置事件" }}
      </el-button>
      <el-button
        v-if="!disabled"
        type="warning"
        size="small"
        @click="handleAdd(model.guideType)"
      >
        添加
      </el-button>
    </div>
    <!-- steps table -->
    <vxe-table
      v-show="model.guideType !== HINTS_GUIDE_TYPE"
      :data="model.steps"
      :auto-resize="true"
      align="center"
    >
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column field="title" title="标题" show-overflow>
        <template #default="{ row, $rowIndex }">
          <el-form-item
            :show-message="false"
            :prop="'steps.' + $rowIndex + '.title'"
            class="element-table-item"
          >
            <el-input v-model="row.title" />
          </el-form-item>
        </template>
      </vxe-column>
      <vxe-column field="element" title="元素" show-overflow>
        <template #default="{ row, $rowIndex }">
          <el-form-item
            :show-message="false"
            :prop="'steps.' + $rowIndex + '.element'"
            class="element-table-item"
          >
            <el-input v-model="row.element" />
          </el-form-item>
        </template>
      </vxe-column>
      <vxe-column field="intro" title="介绍" show-overflow>
        <template #default="{ row, $rowIndex }">
          <el-form-item
            :show-message="false"
            :prop="'steps.' + $rowIndex + '.intro'"
            :rules="rules['steps.intro']"
            class="element-table-item"
          >
            <el-input v-model="row.intro" />
          </el-form-item>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="150" show-overflow>
        <template #default="{ rowIndex }">
          <el-button
            icon="el-icon-setting"
            type="text"
            size="mini"
            @click="handleSetItemEvent(rowIndex)"
          >
            {{ disabled ? "查看事件" : "设置事件" }}
          </el-button>
          <el-button
            v-if="!disabled"
            icon="fa fa-trash-o"
            type="text"
            size="mini"
            @click="handleRemove(rowIndex)"
          >
            删除
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- hints table -->
    <vxe-table
      v-show="model.guideType === HINTS_GUIDE_TYPE"
      :data="model.hints"
      :auto-resize="true"
      align="center"
      class="element-table"
    >
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column field="element" title="元素" show-overflow>
        <template #default="{ row, $rowIndex }">
          <el-form-item
            :show-message="false"
            :prop="'hints.' + $rowIndex + '.element'"
            :rules="rules['hints.element']"
            class="element-table-item"
          >
            <el-input v-model="row.element" />
          </el-form-item>
        </template>
      </vxe-column>
      <vxe-column field="hint" title="介绍" show-overflow>
        <template #default="{ row, $rowIndex }">
          <el-form-item
            :show-message="false"
            :prop="'hints.' + $rowIndex + '.hint'"
            :rules="rules['hints.hint']"
            class="element-table-item"
          >
            <el-input v-model="row.hint" />
          </el-form-item>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="150" show-overflow>
        <template #default="{ rowIndex }">
          <el-button
            icon="el-icon-setting"
            type="text"
            size="mini"
            @click="handleSetItemEvent(rowIndex)"
          >
            {{ disabled ? "查看事件" : "设置事件" }}
          </el-button>
          <el-button
            v-if="!disabled"
            icon="fa fa-trash-o"
            type="text"
            size="mini"
            @click="handleRemove(rowIndex)"
          >
            删除
          </el-button>
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 设置属性 -->
    <vxe-modal
      v-model="attrModalVisible"
      :resize="true"
      width="500"
      height="300"
      title="设置属性"
      show-zoom
      destroy-on-close
      :showFooter="!disabled"
    >
      <attr-form :attrForm="model.guideAttr" :disabled="disabled" />
      <template v-slot:footer>
        <el-button type="warning" @click="resetAttrModel">还原</el-button>
        <el-button type="primary" @click="attrModalVisible = false">
          确定
        </el-button>
        <el-button type="info" @click="attrModalVisible = false">
          取消
        </el-button>
      </template>
    </vxe-modal>

    <!-- 设置公共事件 -->
    <vxe-modal
      v-model="eventModalVisible"
      :resize="true"
      width="1024"
      height="600"
      title="设置事件"
      show-zoom
      destroy-on-close
      :showFooter="!disabled"
    >
      <event-form :eventForm="model.guideEvents" :disabled="disabled" />
      <template v-slot:footer>
        <el-button type="warning" @click="resetEventsModel">还原</el-button>
        <el-button type="primary" @click="eventModalVisible = false">
          确定
        </el-button>
        <el-button type="info" @click="eventModalVisible = false">
          取消
        </el-button>
      </template>
    </vxe-modal>

    <!-- 设置step单项事件 -->
    <vxe-modal
      ref="itemEventModalRef"
      v-model="itemEventModalVisible"
      :resize="true"
      width="1024"
      height="600"
      title="设置事件"
      show-zoom
      destroy-on-close
      :showFooter="!disabled"
      @close="onItemEventClose"
    >
      <event-form :eventForm="currItemEvent" :disabled="disabled" />
      <template v-slot:footer>
        <el-button type="primary" @click="itemEventModalConfirm">
          确定
        </el-button>
        <el-button type="info" @click="onItemEventCancel"> 取消 </el-button>
      </template>
    </vxe-modal>
  </el-form>
</template>

<script>
import AttrForm from "./attrForm";
import EventForm from "./eventForm";
import { mapGetters } from "vuex";

const STEPS_GUIDE_TYPE = "steps";
const HINTS_GUIDE_TYPE = "hints";
const CREATE_PAGE_ACTION = "create";

export default {
  components: { AttrForm, EventForm },
  props: {
    viewModel: Object,
    formData: Object,
    model: Object,
    disabled: Boolean,
  },
  computed: {
    ...mapGetters(["leavesRouterPaths"]),
  },
  data() {
    const validateUserIds = (rule, value, callback) => {
      const { isEveryone, userIds } = this.model;
      if (!isEveryone) {
        if (value === "" || (Array.isArray(userIds) && userIds.length <= 0) ) {
          callback(new Error("请选择用户"));
        }
      }
      callback();
    };
    return {
      STEPS_GUIDE_TYPE,
      HINTS_GUIDE_TYPE,
      CREATE_PAGE_ACTION,
      attrModalVisible: false,
      eventModalVisible: false,
      itemEventModalVisible: false,
      guideAttrBackup: undefined,
      guideEventsBackup: undefined,
      currItemEvent: undefined,
      currRow: 0,
      // 表单校验
      rules: {
        guideName: [
          {
            required: true,
            message: "请输入向导名称",
            trigger: "blur",
          },
        ],
        modulePath: [
          {
            required: true,
            message: "请选择模块路径",
            trigger: "change",
          },
        ],
        userIds: [{ validator: validateUserIds, trigger: "change" }],
        "steps.intro": [
          {
            required: true,
            trigger: "blur",
          },
        ],
        "hints.element": [
          {
            required: true,
            trigger: "blur",
          },
        ],
        "hints.hint": [
          {
            required: true,
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.initElementData();
    this.initBackUpData();
  },
  methods: {
    // 初始化备份数据，用于设置属性、事件还原操作
    initBackUpData() {
      const { guideAttr, guideEvents } = this.model;
      this.guideAttrBackup = Object.assign({}, guideAttr);
      this.guideEventsBackup = Object.assign({}, guideEvents);
    },
    handleAdd(guideType) {
      switch (guideType) {
        case STEPS_GUIDE_TYPE:
          this.arrayPush(
            this.model.steps,
            this.viewModel.controlData.guideStepModel
          );
          break;
        case HINTS_GUIDE_TYPE:
          this.arrayPush(
            this.model.hints,
            this.viewModel.controlData.guideHintsModel
          );
          break;
        default:
          this.msgError("未知的向导类型【" + guideType + "】");
          break;
      }
    },
    handleSetAttr() {
      this.attrModalVisible = true;
    },
    handleSetEvents() {
      this.eventModalVisible = true;
    },
    arrayPush(array, obj) {
      if (Array.isArray(array)) {
        array.push(Object.assign({}, obj));
      }
    },
    initElementData() {
      if (
        this.viewModel &&
        this.viewModel.pageAction === CREATE_PAGE_ACTION &&
        this.model
      ) {
        const { guideType } = this.model;
        const { guideStepModel, guideHintsModel } = this.viewModel.controlData;
        switch (guideType) {
          case STEPS_GUIDE_TYPE:
            this.model.steps = [Object.assign({}, guideStepModel)];
            break;
          case HINTS_GUIDE_TYPE:
            this.model.hints = [Object.assign({}, guideHintsModel)];
            break;
          default:
            this.msgError("未知的向导类型【" + guideType + "】");
            break;
        }
      }
    },
    handleRemove(rowIndex) {
      const { guideType } = this.model;
      switch (guideType) {
        case STEPS_GUIDE_TYPE:
          this.removeElement(this.model.steps, rowIndex);
          break;
        case HINTS_GUIDE_TYPE:
          this.removeElement(this.model.hints, rowIndex);
          break;
        default:
          this.msgError("未知的向导类型【" + guideType + "】");
          break;
      }
    },
    handleSetItemEvent(rowIndex) {
      this.currRow = rowIndex;
      const { guideType } = this.model;
      switch (guideType) {
        case STEPS_GUIDE_TYPE:
          let { stepEvent } = this.model.steps[rowIndex];
          this.currItemEvent = stepEvent
            ? Object.assign({}, stepEvent)
            : Object.assign({}, this.viewModel.controlData.stepEventModel);
          this.itemEventModalVisible = true;
          break;
        case HINTS_GUIDE_TYPE:
          throw new Error("向导类型【" + guideType + "】未实现");
        default:
          this.msgError("未知的向导类型【" + guideType + "】");
          break;
      }
    },
    itemEventModalConfirm() {
      this.model.steps[this.currRow].stepEvent = Object.assign(
        {},
        this.currItemEvent
      );
      this.itemEventModalVisible = false;
      this.currRow = 0;
      this.currItemEvent = undefined;
    },
    onItemEventCancel() {
      this.resetItemEventModalData();
    },
    onItemEventClose() {
      this.resetItemEventModalData();
    },
    resetItemEventModalData() {
      this.itemEventModalVisible = false;
      this.currItemEvent = undefined;
    },
    removeElement(array, rowIndex) {
      if (Array.isArray(array)) {
        if (array.length > 1 && array.length > rowIndex) {
          array.splice(rowIndex, 1);
        } else {
          this.msgError("只有一条数据了");
        }
      }
    },
    onGuideTypeChange() {
      this.initElementData();
    },
    resetAttrModel() {
      this.resetModalHandle("guideAttr", this.guideAttrBackup);
    },
    resetEventsModel() {
      this.resetModalHandle("guideEvents", this.guideEventsBackup);
    },
    resetModalHandle(attrKey, backupData) {
      this.$confirm("是否需要还原数据？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.model[attrKey] = Object.assign({}, backupData);
        })
        .catch(() => {});
    },
    selectAllUser() {
      const { userOptions } = this.viewModel.controlData;
      if (this.model.userIds.length < userOptions.length) {
        const userIds = [];
        userOptions.map((item) => {
          userIds.push(item.userId);
        });
        this.model.userIds = userIds;
      } else {
        this.model.userIds = [];
      }
    },
    onIsEveryoneChange(val) {
      if (val) {
        this.model.userIds = [];
      }
    },
  },
};
</script>

<style scoped lang="scss">
.element-btns {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-end;
  padding: 10px 0;
}
.mix-item {
  display: flex;
  flex-flow: row nowrap;
}
.element-table-item {
  margin-bottom: 0;
}
</style>
